#!/usr/bin/env python2
#coding:utf-8
"""
 Author:   Rusty Stiles
 Purpose: Read in data from columned files and produces graphs
 Created: 06/09/2011
"""
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg


def readfile(filename):
    """Reads filename that is a file structured into columns, where the first 
    column is the x-axis the second column is the y-axis and the optional third
    column is the standard deviation or error, returns (xaxis, yaxis, yerr)
    where xaxis yaxis and yerr are all lists"""
    
    xaxis = []
    yaxis = []
    yerr = []
    with open(filename, 'r') as fil:
        for line in fil:
            data = line
            val = data.split()
            xaxis.append(float(val[0]))
            yaxis.append(float(val[1]))
            try:
                yerr.append(float(val[2]))
            except IndexError:
                pass
    return xaxis, yaxis, yerr


class Graph:
    """Class to initialize a plot, create a graph(with linegraph or bargraph)
       markup the graph (markup) and print the graph to a file(output)"""
    
    def __init__(self):
        """initialize graph to add plots to"""
        self.fig = Figure()
        self.plot = self.fig.add_subplot(111)
        self.plot.hold(True)
        self.canvas = FigureCanvasAgg(self.fig)

    def markup(self, legend = (), title = '', xlabel = '', ylabel = ''):
        """
        legend is a tuple of strings in the order of the added lines, Can use 
        mathtext:
        http://matplotlib.sourceforge.net/users/mathtext.html#mathtext-tutorial
        """
        self.plot.set_xlabel(xlabel)
        self.plot.set_ylabel(ylabel)
        self.plot.set_title(title)
        self.plot.legend(legend,loc='best') 

    def output(self, filename, format = 'eps'):
        """Prints the plot to given filename"""
        self.canvas.print_figure(filename, format = format)
    
        
class Line_graph(Graph):
    """Graph object to draw line graph"""
    
    def add_to_plot(self,xaxis,yaxis,yerr,capsize=0):
        """Set-up a line graph with standard deviations
           xaxis: list containing xaxis points
           yaxis: list of yaxis points
           yerr: list of yaxis points
        """
        self.plot.errorbar(xaxis, yaxis, yerr, capsize = capsize)


class Bar_Graph(Graph):
    """Adds bargraph capability to Graph"""

    def add_to_to_plot(self, xaxis, yaxis, width = 5):
        """Create a bar graph given xaxis and yaxis data lists"""
        self.plot.bar(xaxis, yaxis, width)
    
    
    
if __name__ == '__main__':
    pass